var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
Page({
    data: {
        article: '<div><img src="../static/HeadPortrait_03.jpg"/></div>', //html测试
        userId: '', //当前用户id
        zhongjiang: 4, //判断当前用户是否中奖
		zhongjiangInfoList:[],//中奖详情列表
		zhongjiangInfoListhide: true,//中奖详情列表展示
        SponsorId: '',
        getDetailsData: [],//页面显示数据
		activeData:'',//给数据库的数据
        buttonClicked: false, //防止按钮重复点击
        hiddenmodalput: true, //口令弹窗
        dataKouling: '', //口令
        activeState: '参与抽奖',
		explain:'',//说明
        introduce: '', //介绍
		introduceText: false,//介绍文字
        SeeList: [
            // { SeeAddress: '../static/HeadPortrait_03.jpg' }
        ],
        supportList: [{
            supportName: ''
        }],
        actionSheetHidden: true //分享
    },
    bindGetUserInfo: function(e) {
        // wx.showToast({
        // 	title: '正在处理数据',
        // 	icon: 'loading'
        // })
        util.buttonClicked(this);
        var that = this;
        var userInfo = e.detail.userInfo;
        var index = e.target.dataset.index;
		if (index == "choujiang" && that.data.activeState=='待开奖'){
			that.setData({
				buttonClicked:false
			})
			return;
		}
        if (userInfo) {
            //用户按了允许授权按钮
            // 存一个值证明是第一次点击userInfo
            if (userInfo.nickName == app.globalData.name) {
                if (index == 'choujiang') {
                    this.participate();
                } else {
                    // 成功以后返回按钮状态
                    that.setData({
                        buttonClicked: false
                    })
                    wx.navigateTo({
                        url: '../add/add'
                    })
                }
            } else {
                wx.showToast({
                    title: '正在处理数据',
                    icon: 'loading'
                })
                app.globalData.name = userInfo.nickName;
                wx.login({
                    success: function(res) {
						if (res.code && userInfo.nickName != '' && userInfo.avatarUrl!='') {
                            util.wGet('login', {
                                code: res.code,
                                nickname: userInfo.nickName,
                                avatar: userInfo.avatarUrl,
                                sex: userInfo.gender
                            }).then((res) => {
                                res = res.data;
                                wx.removeStorageSync('accessToken');
                                wx.setStorageSync('accessToken', 'Bearer' + ' ' + res.data.token);
                                var num = wx.getStorageSync('accessToken');
                                util.wGet('user/info', {}).then((res) => {
                                    var res = res.data.data;
                                    app.globalData.userId = res.id;
                                })
                                if (index == 'choujiang') {
                                    that.participate();
                                }
                                if (index == 'addpage') {
                                    // 成功以后返回按钮状态
                                    that.setData({
                                        buttonClicked: false
                                    })
                                    wx.navigateTo({
                                        url: '../add/add'
                                    })
                                }
                            })
                        }
                    }
                })
            }
        } else {
            //用户按了拒绝按钮
            this.setData({
                hiddenmodalput: true
            })
        }
    },
    onShow: function() {
		
	},
    onLoad: function(url) {
        var key = url.key;
        this.setData({
            details: key,
            userId: app.globalData.userId
        });
        this.getDetailsData();
		
    },
    // 获取详情数据
    getDetailsData: function() {
		var that = this;
		util.wGet('user/info', {}).then((res) => {
			that.setData({
				userId:res.data.data.id
			})
			util.wGet('activity/info', {
				activity_id: that.data.details
			}).then((res) => {
				var resData = res.data.data;
				var open_at = 'getDetailsData.open_at';
				that.setData({
					activeData: resData,
				});
				if (resData.open_at) {
					resData.open_at = resData.open_at.slice(0, -3);
				}
				if (resData.explain) {
					//换行
					resData.explain = '<div>' + resData.explain.split('\n').join('</div><div>') + '</div>';
					// 空格
					// for (var i = 0; i < resData.explain.length;i++){
					// 	resData.explain = resData.explain.replace(' ', '&nbsp;');
					// }
					// console.log(resData.explain)
				}
				that.setData({
					getDetailsData: resData,
					SponsorId: resData.user.id
				});
				// console.log(that.data.getDetailsData);
				var introduce = that.data.getDetailsData.introduce;
				var introduceText = introduce.match(/<div>([\s\S]*?)</)[1];
				if (introduceText != '') {
					that.setData({
						introduceText: true
					})
				}
				var explain = that.data.getDetailsData.explain;
				WxParse.wxParse('introduce', 'html', introduce, that, 5);
				WxParse.wxParse('explain', 'html', explain, that, 5);
				if (that.data.getDetailsData.join != '') {
					that.setData({
						activeState: '待开奖'
					});
				}
				util.wGet('join/users', {
					activity_id: that.data.details,
					limit: 18
				}).then((res) => {
					var avatar = [];
					var res = res.data.data;
					if (res.data.length > 20) {
						res.data.length = 20
					}
					for (var i = 0; i < res.data.length; i++) {
						avatar.push({
							'SeeAddress': res.data[i].user.avatar
						})
					}
					that.setData({
						SeeList: avatar
					});
				})

				if (that.data.getDetailsData.status == 3 && that.data.getDetailsData.join != '') {//已结束待开奖
					util.wGet('join/winner', {//中奖后的逻辑
						activity_id: that.data.details
					}).then((res) => {
						var res = res.data.data;
						for (var i = 0; i < res.length; i++) {
							if (res[i].user_id == that.data.userId) {
								that.setData({
									zhongjiang: 1
								});
							} else {
								that.setData({
									zhongjiang: 2
								});
							}
						}
						that.setData({
							zhongjiangList: res
						});
						if (res.length == 0) {
							that.setData({
								zhongjiang: 2
							});
						}
					})
				} else if (that.data.getDetailsData.status == 3 && that.data.getDetailsData.join == ''){
					that.setData({
						zhongjiang: 3
					});
					util.wGet('join/winner', {//中奖后的逻辑
						activity_id: that.data.details
					}).then((res) => {
						var res = res.data.data;
						that.setData({
							zhongjiangList: res
						});
					})
				}
			})
		})
		
        
        
		
    },
	// 中奖用户详情
	zhongjiangInfo:function(){
		var that=this;
		that.setData({
			zhongjiangInfoListhide: !that.data.zhongjiangInfoListhide
		})
		if (that.data.zhongjiangInfoListhide==false){
			util.wGet('address/winuser', {
				activity_id: that.data.details
			}).then((res) => {
				console.log(res.data);
				var resData = res.data.data;
				if (resData.current_page < resData.last_page){
					var dataarr=[];
					for (var i = 0; i < resData.last_page;i++){
						util.wGet('address/winuser', {
							activity_id: that.data.details
						}).then((res) => {
							dataarr.push(res.data.data.data);
						})
					}
					that.setData({
						zhongjiangInfoList: dataarr
					})
				}
				else{
					that.setData({
						zhongjiangInfoList: resData.data,
					})
				}
			})
		}
		
	},
    // 中奖按钮
    zhongjiangaddress: function() {
		var that = this;
		// 判断如果用户拒绝授权
		wx.getSetting({//先获取用户当前的设置
			success(res) {
				if (!res.authSetting['scope.address']) {
					wx.authorize({ 
						scope: 'scope.address',
						success(res) {
							// console.log(res.errMsg);
							//用户授权后执行方法
						},
						fail(res) {
							//用户拒绝授权后执行
							wx.showModal({
								title: '提示',
								content: '请允许授权地址获取更多权限',
								success(res) {
									if (res.confirm) {
										wx.getSetting({
											success(res) {
												if (!res.authSetting['scope.address']) {
													wx.openSetting({});
												} else {
													//打开选择地址
													wx.chooseAddress({
														success: function (res) {
															util.wPost('join/set_address', {
																name: res.userName,
																mobile: res.telNumber,
																code: res.nationalCode || res.postalCode,
																activity_id: that.data.details,
																address: res.provinceName + res.cityName + res.countyName + res.detailInfo
															}).then((res) => {
																wx.showToast({
																	icon: "none",
																	title: '地址输入成功'
																})
															})
														}
													})
												}
											},
											fail(res) {
												// console.log('调用失败')
											}
										})
									} else if (res.cancel) {
									}
								}
							})
						}
					})
				} else {
					//打开选择地址
					wx.chooseAddress({
						success: function (res) {
							util.wPost('join/set_address', {
								name: res.userName,
								mobile: res.telNumber,
								code: res.nationalCode || res.postalCode,
								address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
								activity_id: that.data.details
							}).then((res) => {
								wx.showToast({
									icon: "none",
									title: '地址输入成功'
								})
								console.log(res);
							})
						}
					})
				}
			}
		})
    },
    zhongjiangmore: function() {
        wx.reLaunch({
            url: '../index/index'
        })
    },
    // 手动开奖
    manualAward: function() {
		var that=this;
        util.wPost('activity/lock', {
            activity_id: that.data.details
        }).then((res) => {
            wx.showToast({
				icon: "loading",
                title: '请求数据中',
				duration:2000
            })
			that.manualAwardGetData();
        })
    },
	// 手动开奖后请求数据
	manualAwardGetData: function(){
		var that=this;
		util.wGet('activity/info', {
			activity_id: that.data.details
		}).then((res) => {
			var resData = res.data.data;
			var open_at = 'getDetailsData.open_at';
			if (resData.open_at) {
				resData.open_at = resData.open_at.slice(0, -3);
			}
			if (resData.explain) {
				resData.explain = '<div>' + resData.explain.split('\n').join('</div><div>') + '</div>';
			}
			if (resData.status != 3) {
				setTimeout(function () { that.manualAwardGetData() }, 1000);
			} else {
				that.setData({
					getDetailsData: resData,
					SponsorId: resData.user.id
				});
				var introduce = that.data.getDetailsData.introduce;
				var explain = that.data.getDetailsData.explain;
				WxParse.wxParse('introduce', 'html', introduce, that, 5);
				WxParse.wxParse('explain', 'html', explain, that, 5);
				if (that.data.getDetailsData.join != '') {
					that.setData({
						activeState: '待开奖'
					});
				}
				util.wGet('join/users', {
					activity_id: that.data.details,
					limit: 18
				}).then((res) => {
					var avatar = [];
					var res = res.data.data;
					if (res.data.length > 20) {
						res.data.length = 20
					}
					for (var i = 0; i < res.data.length; i++) {
						avatar.push({
							'SeeAddress': res.data[i].user.avatar
						})
					}
					that.setData({
						SeeList: avatar
					});
				})
				if (that.data.getDetailsData.status == 3) {
					util.wGet('join/winner', {
						activity_id: that.data.details
					}).then((res) => {
						var res = res.data.data;
						for (var i = 0; i < res.length; i++) {
							if (res[i].user_id == app.globalData.userId) {
								that.setData({
									zhongjiang: 1
								});
							} else {
								that.setData({
									zhongjiang: 2
								});
							}
						}
						that.setData({
							zhongjiangList: res
						});
					})
				}
			}
		})
	},
    // 编辑开奖
    editAward: function() {
        var that = this;
		if (that.data.getDetailsData.password == 1){
			wx.showModal({
				title: '提示',
				content: '本公司为了安全着想，口令是后台验证，如果选择编辑，口令将重置',
				confirmText: '前往编辑',
				cancelText: '取消编辑',
				success: function (res) {
					if (res.confirm) {
						var thispageData = that.data.activeData;
						app.globalData.add = thispageData;
						app.globalData.testUrl0 = '';
						app.globalData.testUrl1 = '';
						app.globalData.testUrl2 = '';
						util.wGet('join/users', {
							activity_id: that.data.details,
							limit: 18
						}).then((res) => {
							var res = res.data.data;
							if (res.total == 0) {
								wx.redirectTo({
									url: '../add/add?index=modify'
								})
							} else {
								wx.showToast({
									icon: "none",
									title: "已有人参与，不能编辑"
								})
								for (var i = 0; i < res.data.length; i++) {
									avatar.push({
										'SeeAddress': res.data[i].user.avatar
									})
								}
								var joinnum = 'getDetailsData.user_num';
								var joinState = 'getDetailsData.join';
								that.setData({
									SeeList: avatar,
									[joinnum]: res.total,
									[joinState]: res.data
								});
							}
						})
					} else if (res.cancel) { }
				}
			})
		}else{
			var thispageData = that.data.activeData;
			app.globalData.add = thispageData;
			app.globalData.testUrl0 = '';
			app.globalData.testUrl1 = '';
			app.globalData.testUrl2 = '';
			util.wGet('join/users', {
				activity_id: that.data.details,
				limit: 18
			}).then((res) => {
				var res = res.data.data;
				if (res.total == 0) {
					wx.redirectTo({
						url: '../add/add?index=modify'
					})
				} else {
					wx.showToast({
						icon: "none",
						title: "已有人参与，不能编辑"
					})
					for (var i = 0; i < res.data.length; i++) {
						avatar.push({
							'SeeAddress': res.data[i].user.avatar
						})
					}
					var joinnum = 'getDetailsData.user_num';
					var joinState = 'getDetailsData.join';
					that.setData({
						SeeList: avatar,
						[joinnum]: res.total,
						[joinState]: res.data
					});
				}
			})
		}
        

    },
    //   复制
    BtnExplain: function(e) {
        var self = this;
        wx.setClipboardData({
            data: self.data.getDetailsData.copy,
            success: function(res) {
                // self.setData({copyTip:true}),
                wx.showToast({
                    icon: "none",
                    title: "复制成功"
                })
            }
        });
    },
    // 口令
    cancelM: function(e) {
        // 成功以后返回按钮状态
        this.setData({
            buttonClicked: false
        })
        this.setData({
            hiddenmodalput: true,
        })
    },
    // 口令传值
    confirmM: function(e) {
        var that = this;
        if (that.data.dataKouling == '') {
            wx.showToast({
                title: '口令不能为空',
                icon: 'none'
            })
            return;
        }

        // var num = wx.getStorageSync('accessToken');
        that.setData({
            hiddenmodalput: true,
        })
        util.wPost('join/add', {
            activity_id: that.data.details,
            password: that.data.dataKouling
        }).then((res) => {
            var res = res.data;
            var code = res.code;
            if (code == 1) {
                wx.showToast({
                    icon: "none",
                    title: res.msg
                })
            } else {
                that.setData({
                    activeState: '待开奖'
                })
                // 成功以后返回按钮状态
                that.setData({
                    buttonClicked: false
                })
				var content = '开奖时间为' + that.data.getDetailsData.open_at.slice(0, -3) + ' 请留意开奖通知，不要错过哦~';
				if (that.data.getDetailsData.wintype!=1){
					content = '最迟开奖时间为' + that.data.getDetailsData.open_at.slice(0, -3) + ' 请留意开奖通知，不要错过哦~';
				}
                wx.showModal({
                    title: '报名成功',
                    showCancel: false,
					content: content,
                    success: function(res) {
                        if (res.confirm) {
                            util.wGet('join/users', {
                                activity_id: that.data.details,
                                limit: 18
                            }).then((res) => {
                                var avatar = [];
                                var res = res.data.data;
                                if (res.data.length > 20) {
                                    res.data.length = 20
                                }
                                for (var i = 0; i < res.data.length; i++) {
                                    avatar.push({
                                        'SeeAddress': res.data[i].user.avatar
                                    })
                                }
                                var joinnum = 'getDetailsData.user_num';
                                var joinState = 'getDetailsData.join';
                                that.setData({
                                    SeeList: avatar,
                                    [joinnum]: res.total,
                                    [joinState]: res.data
                                });
                            })
                            // return;
                            // var url = that.data.details;
                            // wx.redirectTo({
                            //   url: '../activity/activity?key=' + url
                            // })
                        } else if (res.cancel) {}
                    }
                })
            }
        })
    },
    kouling: function(e) {
        this.setData({
            dataKouling: e.detail.value
        })
    },
    // 参与抽奖
    participate: function() {
        var that = this;
        if (that.data.activeState == "待开奖") {
            // 成功以后返回按钮状态
            that.setData({
                buttonClicked: false
            })
            return;
        } else {
            if (that.data.getDetailsData.password == 1) {
                this.setData({
                    hiddenmodalput: false,
                })
            } else {
                util.wPost('join/add', {
                    activity_id: that.data.details,
                    password: ''
                }).then((res) => {
                    if (res.data.code == 1) {
                        wx.showToast({
                            title: res.data.msg, //提示文字
                            duration: 2000, //显示时长
                            mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
                            icon: none, //图标，支持"success"、"loading"  
                        })
                    } else {
                        that.setData({
                            activeState: '待开奖'
                        })
                        // 成功以后返回按钮状态
                        that.setData({
                            buttonClicked: false
                        })
						var content = '开奖时间为' + that.data.getDetailsData.open_at.slice(0, -3) + ' 请留意开奖通知，不要错过哦~';
						if (that.data.getDetailsData.wintype != 1) {
							content = '最迟开奖时间为' + that.data.getDetailsData.open_at.slice(0, -3) + ' 请留意开奖通知，不要错过哦~';
						}
                        wx.showModal({
                            title: '报名成功',
                            showCancel: false,
							content: content,
                            success: function(res) {
                                if (res.confirm) {
                                    util.wGet('join/users', {
                                        activity_id: that.data.details,
                                        limit: 18
                                    }).then((res) => {
                                        var avatar = [];
                                        var res = res.data.data;
                                        if (res.data.length > 20) {
                                            res.data.length = 20
                                        }
                                        for (var i = 0; i < res.data.length; i++) {
                                            avatar.push({
                                                'SeeAddress': res.data[i].user.avatar
                                            })
                                        }
                                        var joinnum = 'getDetailsData.user_num';
                                        var joinState = 'getDetailsData.join';
                                        that.setData({
                                            SeeList: avatar,
                                            [joinnum]: res.total,
                                            [joinState]: res.data
                                        });
                                    })
                                } else if (res.cancel) {}
                            }
                        })
                    }


                })
            }
        }
    },
    // 分享给朋友
    onShareAppMessage: function() {
        return {
            title: '抽奖进行时',
            desc: '快来抽奖吧',
            path: '/pages/index/index?key=' + this.data.details

        }
    },
    actioncnt: function() {
        var that = this;
        wx.showActionSheet({
            itemList: ['邀请微信好友'],
            success: function(res) {
                var tapIndex = res.tapIndex;
                if (tapIndex == 0) {
                    // document.getElementById('share').click();
                    that.onShareAppMessage();
                }
            },
            fail: function(res) {}
        })
    },
    map: function() {
        wx.navigateTo({ //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
            url: "/pages/add/add"
        })
    },
    showAcitvityUsers: function() {
        wx.navigateTo({
            url: '../whole/whole?activity_id=' + this.data.details
        })
    }, //分享
    listenerButton: function() {
        this.setData({
            actionSheetHidden: !this.data.actionSheetHidden
        });
    },
    listenerActionSheet: function() {
        this.setData({
            actionSheetHidden: !this.data.actionSheetHidden
        })
    },
    // 给后台fromID
    orderSign: function(e) {
        var fId = e.detail.formId;
        util.wPost('forms/add', {
            form_id: fId
        })
	}
	//   客服消息
	, handleContact(e) {
		// console.log(e.path)
		// console.log(e.query)
	}
})